package ynu.edu.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ynu.edu.entity.Orders;
import ynu.edu.entity.OrderDetailet;
import ynu.edu.repository.OrdersRepository;
import ynu.edu.repository.OrderDetailetRepository;

import java.time.LocalDateTime;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class OrdersService {

    private static final Logger log = LoggerFactory.getLogger(OrdersService.class);

    @Autowired
    private OrdersRepository ordersRepository;

    @Autowired
    private OrderDetailetRepository orderDetailetRepository;

    @Transactional
    public Orders createOrders(Orders orderData) {
        try {
            // 设置订单状态为未支付(0)
            orderData.setOrderState(0);
            // 设置下单时间
            orderData.setOrderDate(LocalDateTime.now());
            // 保存订单主表
            Orders savedOrder = ordersRepository.save(orderData);
            
            // 保存订单详情
            if (orderData.getOrderItems() != null && !orderData.getOrderItems().isEmpty()) {
                for (OrderDetailet item : orderData.getOrderItems()) {
                    item.setOrderId(savedOrder.getOrderId());  // 设置关联的订单ID
                    orderDetailetRepository.save(item);
                }
            }
            
            return savedOrder;
        } catch (Exception e) {
            log.error("Failed to create order", e);
            throw new RuntimeException("创建订单失败: " + e.getMessage());
        }
    }

    public List<Orders> listOrdersByUserId(Integer userId) {
        return ordersRepository.findByUserId(userId);
    }

    public Orders getOrdersById(Integer orderId) {
        return ordersRepository.findById(orderId)
                .orElseThrow(() -> new RuntimeException("订单不存在"));
    }

    public List<OrderDetailet> getOrderDetailetByOrderId(Integer orderId) {
        log.info("Getting order details for orderId: {}", orderId);
        List<OrderDetailet> details = orderDetailetRepository.findByOrderId(orderId);
        log.info("Found {} order details", details.size());
        return details;
    }

    @Transactional
    public Orders updateOrderState(Integer orderId, Integer orderState) {
        Orders order = ordersRepository.findById(orderId)
                .orElseThrow(() -> new RuntimeException("订单不存在"));
        order.setOrderState(orderState);
        return ordersRepository.save(order);
    }
} 